import os
import pandas as pd
import argparse


# 查找服务器中没有的文件
def parse_arguments():
    parser = argparse.ArgumentParser(description='Check file existence based on CSV records')
    parser.add_argument('--csv_file', required=True, help='CSV file path containing file records')
    parser.add_argument('--base_directory', required=True, help='Base directory for file paths')
    parser.add_argument('--output_csv', required=True, help='Output CSV file path for missing files')
    return parser.parse_args()


def read_csv_data(csv_file):
    """从 CSV 文件读取数据"""
    df = pd.read_csv(csv_file)
    print("read_csv_data DataFrame示例：", df.head())
    return df


def assemble_file_paths(df, base_directory):
    """根据数据帧组装文件路径"""
    file_paths = []
    for _, row in df.iterrows():
        absolutepath = row['ABSOLUTEPATH']
        sysfilename = row['SYSFILENAME']
        filename_without_extension = os.path.splitext(sysfilename)[0]
        last_two_chars = filename_without_extension[-2:]
        file_path = os.path.join(base_directory, absolutepath, last_two_chars, sysfilename)
        file_paths.append((row, file_path))
    return file_paths


def check_files_exist(file_paths):
    """检查文件路径是否存在，并返回未找到的文件路径"""
    missing_files = []
    for row, file_path in file_paths:
        if os.path.exists(file_path):
            print(f"文件存在: {file_path}")
        else:
            print(f"文件不存在: {file_path}")
            row['file_not_found_path'] = file_path
            missing_files.append(row)
    return missing_files


def save_missing_files_to_csv(missing_files, output_csv):
    """将未找到的文件路径保存到 CSV 文件"""
    if not missing_files:
        print("No missing files to save.")
        return

    df_missing = pd.DataFrame(missing_files)

    # 打印 DataFrame 的列名和示例数据
    print("DataFrame列名：", df_missing.columns.tolist())
    print("DataFrame 示例数据：", df_missing.head())

    # 确保包含所有期望的列
    expected_columns = ['id', 'ABSOLUTEPATH', 'SYSFILENAME', 'OPERATIONCODE', 'OPERATIONID', 'PHYFILENAME', 'FILETYPE',
                        'FILESIZE', 'PERSONID', 'PERSONNAME', 'OPERATIONNAME', 'file_not_found_path']
    missing_columns = [col for col in expected_columns if col not in df_missing.columns]
    for col in missing_columns:
        df_missing[col] = ''  # 为缺失的列填充空值

    df_missing.to_csv(output_csv, index=False, columns=expected_columns)


if __name__ == '__main__':
    args = parse_arguments()

    # 从 CSV 文件中读取数据
    df = read_csv_data(args.csv_file)

    # 组装文件路径
    file_paths = assemble_file_paths(df, args.base_directory)

    # 检查文件是否存在
    missing_files = check_files_exist(file_paths)

    # 将未找到的文件路径保存到 CSV 文件
    save_missing_files_to_csv(missing_files, args.output_csv)

    print(f"Missing files saved to {args.output_csv}")
